// diff_util.cc - DiffUtil的显式实例化和辅助功能
#ifdef LOG_TAG
#undef LOG_TAG
#endif
#define LOG_TAG "YourTagName"
#include "diff_util.h"
#include "paging_controller.h"  // 获取PagingItem定义
#include <hilog/log.h>
#include <chrono>

#define LOG_TAG "DiffUtil"
#define LOGI(...) OH_LOG_Print(LOG_APP, LOG_INFO, 0, LOG_TAG, __VA_ARGS__)
#define LOGE(...) OH_LOG_Print(LOG_APP, LOG_ERROR, 0, LOG_TAG, __VA_ARGS__)
#define LOGD(...) OH_LOG_Print(LOG_APP, LOG_DEBUG, 0, LOG_TAG, __VA_ARGS__)
#define LOGW(...) OH_LOG_Print(LOG_APP, LOG_WARN, 0, LOG_TAG, __VA_ARGS__)  // 添加LOGW宏定义

// ============ DiffStats 结构体定义 ============
struct DiffStats {
    size_t totalDiffs = 0;           // 总的diff操作次数
    size_t totalInsertions = 0;      // 总插入数
    size_t totalDeletions = 0;       // 总删除数
    size_t totalMoves = 0;           // 总移动数
    size_t totalChanges = 0;         // 总修改数
    long long totalTimeMs = 0;       // 总耗时（毫秒）
    long long maxTimeMs = 0;         // 最大单次耗时
    long long minTimeMs = LLONG_MAX; // 最小单次耗时
    
    // 更新统计信息
    void update(size_t insertions, size_t deletions, size_t moves, size_t changes, long long timeMs) {
        totalDiffs++;
        totalInsertions += insertions;
        totalDeletions += deletions;
        totalMoves += moves;
        totalChanges += changes;
        totalTimeMs += timeMs;
        
        if (timeMs > maxTimeMs) maxTimeMs = timeMs;
        if (timeMs < minTimeMs) minTimeMs = timeMs;
    }
    
    // 重置统计信息
    void reset() {
        totalDiffs = 0;
        totalInsertions = 0;
        totalDeletions = 0;
        totalMoves = 0;
        totalChanges = 0;
        totalTimeMs = 0;
        maxTimeMs = 0;
        minTimeMs = LLONG_MAX;
    }
    
    // 获取平均耗时
    long long getAverageTimeMs() const {
        return totalDiffs > 0 ? totalTimeMs / totalDiffs : 0;
    }
    
    // 打印统计信息
    void log() const {
        LOGI("DiffStats: diffs=%zu, ins=%zu, del=%zu, mov=%zu, chg=%zu, avgTime=%lldms, maxTime=%lldms",
             totalDiffs, totalInsertions, totalDeletions, totalMoves, totalChanges,
             getAverageTimeMs(), maxTimeMs);
    }
};

// ============ 显式模板实例化 ============
// 注意：主要实现已经在diff_util.h中作为内联函数

// 为基础类型提供显式实例化（如果需要直接比较基础类型）
template class DiffUtil<std::string>;
template class DiffUtil<int>;
template class DiffUtil<double>;
template class DiffUtil<float>;
template class DiffUtil<long>;

// 为PagingItem智能指针提供显式实例化（这是主要用途）
// T = std::shared_ptr<PagingItem<X>>，其中X是实际的数据类型
template class DiffUtil<std::shared_ptr<PagingItem<std::string>>>;
template class DiffUtil<std::shared_ptr<PagingItem<int>>>;
template class DiffUtil<std::shared_ptr<PagingItem<double>>>;
template class DiffUtil<std::shared_ptr<PagingItem<float>>>;
template class DiffUtil<std::shared_ptr<PagingItem<long>>>;

// LambdaItemCallback显式实例化
template class LambdaItemCallback<std::string>;
template class LambdaItemCallback<int>;
template class LambdaItemCallback<double>;
template class LambdaItemCallback<float>;
template class LambdaItemCallback<long>;

// 为PagingItem智能指针类型的LambdaItemCallback提供实例化
template class LambdaItemCallback<std::shared_ptr<PagingItem<std::string>>>;
template class LambdaItemCallback<std::shared_ptr<PagingItem<int>>>;
template class LambdaItemCallback<std::shared_ptr<PagingItem<double>>>;
template class LambdaItemCallback<std::shared_ptr<PagingItem<float>>>;
template class LambdaItemCallback<std::shared_ptr<PagingItem<long>>>;

// ============ 辅助命名空间实现 ============

namespace DiffUtilHelper {
    
    // 全局统计对象
    DiffStats globalStats;
    
    // 日志辅助函数
    void logDiffOperation(const char* operation, size_t oldSize, size_t newSize) {
        LOGD("Diff operation: %s, old=%zu, new=%zu", operation, oldSize, newSize);
    }
    
    // 性能监控辅助函数
    void logPerformance(const char* operation, long long milliseconds) {
        if (milliseconds > 100) {
            LOGW("Slow diff operation: %s took %lld ms", operation, milliseconds);
        } else {
            LOGD("Diff operation: %s completed in %lld ms", operation, milliseconds);
        }
    }
    
    // 计时器类，用于测量diff操作性能
    class Timer {
    private:
        std::chrono::steady_clock::time_point start_;
        const char* operation_;
        
    public:
        explicit Timer(const char* operation) 
            : start_(std::chrono::steady_clock::now()), operation_(operation) {}
        
        ~Timer() {
            auto end = std::chrono::steady_clock::now();
            auto duration = std::chrono::duration_cast<std::chrono::milliseconds>(end - start_).count();
            logPerformance(operation_, duration);
        }
        
        long long elapsed() const {
            auto end = std::chrono::steady_clock::now();
            return std::chrono::duration_cast<std::chrono::milliseconds>(end - start_).count();
        }
    };
    
    // 辅助函数：统计DiffResult中的操作数量
    template<typename T>
    void updateStats(const typename DiffUtil<T>::DiffResult& result, long long timeMs) {
        size_t insertions = 0, deletions = 0, moves = 0, changes = 0;
        
        for (const auto& op : result.getOperations()) {
            switch (op.type) {
                case DiffUtil<T>::OpType::INSERT:
                    insertions += op.count;
                    break;
                case DiffUtil<T>::OpType::REMOVE:
                    deletions += op.count;
                    break;
                case DiffUtil<T>::OpType::MOVE:
                    moves += op.count;
                    break;
                case DiffUtil<T>::OpType::CHANGE:
                    changes += op.count;
                    break;
                default:
                    break;
            }
        }
        
        globalStats.update(insertions, deletions, moves, changes, timeMs);
    }
    
    // 带性能统计的diff计算包装函数
    template<typename T>
    typename DiffUtil<T>::DiffResult calculateDiffWithStats(
        const std::vector<T>& oldList,
        const std::vector<T>& newList,
        const typename DiffUtil<T>::ItemCallback& callback,
        bool detectMoves = true) {
        
        Timer timer("calculateDiff");
        
        auto result = DiffUtil<T>::calculateDiff(oldList, newList, callback, detectMoves);
        
        updateStats<T>(result, timer.elapsed());
        
        // 每100次操作打印一次统计信息
        if (globalStats.totalDiffs % 100 == 0) {
            globalStats.log();
        }
        
        return result;
    }
    
    // 显式实例化辅助函数模板
    template typename DiffUtil<std::string>::DiffResult 
        calculateDiffWithStats<std::string>(
            const std::vector<std::string>&,
            const std::vector<std::string>&,
            const DiffUtil<std::string>::ItemCallback&, bool);
    
    template typename DiffUtil<int>::DiffResult 
        calculateDiffWithStats<int>(
            const std::vector<int>&,
            const std::vector<int>&,
            const DiffUtil<int>::ItemCallback&, bool);
            
    // 重置全局统计
    void resetStats() {
        globalStats.reset();
        LOGI("DiffUtil statistics reset");
    }
    
    // 获取当前统计信息
    const DiffStats& getStats() {
        return globalStats;
    }
}